﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;
using System.Collections;

namespace WebUI.EditPages
{
    public partial class EditBranch : BasePage
    {
        Branches branch;
        int branchID;
        string mode;

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (Request.QueryString[MODE] == null)
            {
                CloseDlg(0);
                return;
            }

            mode = Request.QueryString[MODE];

            if (Request.QueryString[ID] == null && (mode == EDIT_MODE || mode == VIEW_MODE))
            {
                CloseDlg(0);
                return;
            }

            branchID = Request.QueryString[ID] != null ? int.Parse(Request.QueryString[ID]) : 0;
            if (mode == ADD_MODE)
                btnSave.Enabled = false;


            if (!IsPostBack && mode != ADD_MODE)
            {
                LoadInfo();
            }
            else if (!IsPostBack)
            {
                editBranch.Active = true;
                //editBranch.Name = "Tb Mobile";
                //editBranch.ABN = "51 134 546 268";
                //editBranch.Address = "12 Bis Le Van Tam";
                //editBranch.Phone = "02 3416 7840";
                //editBranch.Fax = "02 3416 7823";
            }

            if (mode != ADD_MODE)
                editBranch.SetVisibleCopy(false);
        }

        public void btnSave_OnClick(Object sender, EventArgs e)
        {
            Save();
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue={0};", 1), true);
        }

        private bool Save()
        {
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();

            branch = new Branches();
            string oldFilter = branch.Filter;
            try
            {
                tx.BeginTransaction();
                if (mode == ADD_MODE)
                {
                    branch.AddNew();
                    branch.Deleted = false;
                }
                else
                {
                    branch.LoadByPrimaryKey(branchID);
                }

                branch.LastModifiedByUser = SessionUser.ID;
                branch.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                branch.Name = editBranch.Name;
                branch.Address = editBranch.Address;
                branch.Phone = editBranch.Phone;
                branch.ABN = editBranch.ABN;
                branch.Fax = editBranch.Fax;
                branch.Active = editBranch.Active;
                branch.IsHeadQuarter = false;
                branch.Save();

                if (editBranch.CopyFromHeadQuarter && mode == ADD_MODE)
                {
                    Branches headQuarter = Branches.GetHeadQuarter();

                    //copy brand
                    Brands brands = Brands.LoadAllActiveBrands(headQuarter.ID);
                    Brands newBrands = new Brands();
                    Hashtable brandMap = new Hashtable();
                    for (int i = 0; i < brands.RowCount; i++)
                    {
                        newBrands.AddNew();
                        newBrands.BranchID = branch.ID;
                        newBrands.BrandName = brands.BrandName;
                        newBrands.Deleted = false;
                        newBrands.LastModifiedByUser = SessionUser.ID;
                        newBrands.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                        newBrands.s_StockKey = brands.s_StockKey;
                        brands.MoveNext();
                    }

                    newBrands.Save();

                    newBrands.Rewind();
                    brands.Rewind();
                    for (int i = 0; i < brands.RowCount; i++)
                    {
                        brandMap[brands.ID] = newBrands.ID;
                        brands.MoveNext();
                        newBrands.MoveNext();
                    }

                    //copy category
                    Categories cats = Categories.GetAllActiveCategories(headQuarter.ID);
                    Categories newCats = new Categories();
                    Hashtable  catMap = new Hashtable();
                    for (int i = 0; i < cats.RowCount; i++)
                    {
                        newCats.AddNew();
                        newCats.BranchID = branch.ID;
                        newCats.s_CategoryName = cats.s_CategoryName;
                        newCats.s_ParentID = cats.s_ParentID;
                        newCats.s_Level = cats.s_Level;
                        newCats.s_VisibleToCustomer = cats.s_VisibleToCustomer;
                        newCats.s_IsDefault = cats.s_IsDefault;
                        newCats.s_IsDealerOnly = cats.s_IsDealerOnly;
                        newCats.Deleted = false;
                        newCats.LastModifiedByUser = SessionUser.ID;
                        newCats.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                        newCats.s_StockKey = cats.s_StockKey;
                        cats.MoveNext();
                    }

                    newCats.Save();

                    newCats.Rewind();
                    cats.Rewind();
                    for (int i = 0; i < cats.RowCount; i++)
                    {
                        catMap[cats.ID] = newCats.ID;
                        cats.MoveNext();
                        newCats.MoveNext();
                    }

                    newCats.Rewind();
                    cats.Rewind();
                    for (int i = 0; i < newCats.RowCount; i++)
                    {
                        if (newCats.s_ParentID != "")
                            newCats.ParentID = (int)catMap[newCats.ParentID];
                        newCats.MoveNext();
                    }

                    newCats.Save();

                    //copy product
                    Products pd = Products.GetAllActiveProducts(headQuarter.ID);
                    Products newPd = new Products();
                    for (int i = 0; i < pd.RowCount; i++)
                    {
                        if (brandMap.ContainsKey(pd.BrandID) && catMap.ContainsKey(pd.CategoryID))
                        {
                            newPd.AddNew();
                            newPd.s_BarCode = pd.s_BarCode;
                            newPd.BranchID = branch.ID;
                            newPd.BrandID = (int)brandMap[pd.BrandID];
                            newPd.CategoryID = (int)catMap[pd.CategoryID];
                            newPd.Cost = 0;
                            newPd.DealerPrice = 0;
                            newPd.SalePrice = 0;
                            newPd.Deleted = false;
                            newPd.s_Description = pd.s_Description;
                            newPd.s_GST = pd.s_GST;
                            newPd.s_IMEIAvailable = pd.s_IMEIAvailable;
                            newPd.s_IsDealerOnly = pd.s_IsDealerOnly;
                            newPd.s_IsHomeProduct = pd.s_IsHomeProduct;
                            newPd.s_IsHotProduct = pd.s_IsHotProduct;
                            newPd.s_IsNewArrival = pd.s_IsNewArrival;
                            newPd.LastModifiedByUser = SessionUser.ID;
                            newPd.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                            newPd.s_Picture = pd.s_Picture;
                            newPd.s_ProductName = pd.s_ProductName;
                            newPd.Quantity = 0;
                            newPd.s_RegularPrice = "";
                            newPd.SoldQuantity = 0;
                            newPd.s_Thumbnail = "";
                            newPd.StockKey = pd.StockKey;
                        }
                        
                        pd.MoveNext();
                    }

                    newPd.Save();

                    CustomerType types = CustomerType.GetAllActiveCustomerType(headQuarter.ID);
                    CustomerType newTypes = new CustomerType();
                    for (int i = 0; i < types.RowCount; i++)
                    {
                        newTypes.AddNew();
                        newTypes.BranchID = branch.ID;
                        newTypes.s_DealerPrice = types.s_DealerPrice;
                        newTypes.Deleted = false;
                        newTypes.s_TypeName = types.s_TypeName;
                        newTypes.LastModifiedByUser = SessionUser.ID;
                        newTypes.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);

                        types.MoveNext();
                    }

                    newTypes.Save();

                    //copy network
                    Networks net = Networks.GetAllActiveNetworks(headQuarter.ID);
                    Networks newNet = new Networks();
                    for (int i = 0; i < net.RowCount; i++)
                    {
                        newNet.AddNew();
                        newNet.BranchID = branch.ID;
                        newNet.s_CommissionEnquiryEmail = "";
                        newNet.s_CommissionEnquiryName = "";
                        newNet.s_CommissionEnquiryPhone = "";
                        newNet.s_DealerCode = "";
                        newNet.s_DealerManagerEmail = "";
                        newNet.s_DealerManagerName = "";
                        newNet.s_DealerManagerPhone = "";
                        newNet.Deleted = false;
                        newNet.s_NetworkName = net.s_NetworkName;
                        newNet.s_OtherEmail = "";
                        newNet.s_OtherName = "";
                        newNet.s_OtherPhone = "";
                        newNet.LastModifiedByUser = SessionUser.ID;
                        newNet.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                        newNet.s_PostalAddress = "";
                        net.MoveNext();
                    }

                    newNet.Save();

                    //copy RepairModel
                    RepairModels models = RepairModels.GetAllActiveModels(headQuarter.ID);
                    RepairModels newModels = new RepairModels();
                    Hashtable repairModelMap = new Hashtable();
                    for (int i = 0; i < models.RowCount; i++)
                    {
                        if (brandMap.ContainsKey(models.BrandID))
                        {
                            newModels.AddNew();
                            newModels.Deleted = false;
                            newModels.BranchID = branch.ID;

                            newModels.BrandID = (int)brandMap[models.BrandID];

                            newModels.s_ModelName = models.s_ModelName;
                            newModels.LastModifiedByUser = SessionUser.ID;
                            newModels.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                        }
                        models.MoveNext();
                    }

                    newModels.Save();

                    models.Rewind();
                    newModels.Rewind();
                    for (int i = 0; i < models.RowCount; i++)
                    {
                        repairModelMap[models.ID] = newModels.ID;
                        models.MoveNext();
                        newModels.MoveNext();
                    }

                    ProblemCategories probCat = ProblemCategories.GetAllActiveCategories(headQuarter.ID);
                    ProblemCategories newProbCat = new ProblemCategories();
                    Hashtable probCatMap = new Hashtable();
                    for (int i = 0; i < probCat.RowCount; i++)
                    {
                        newProbCat.AddNew();
                        newProbCat.BranchID = branch.ID;
                        newProbCat.Deleted = false;
                        newProbCat.LastModifiedByUser = SessionUser.ID;
                        newProbCat.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                        newProbCat.s_ProblemCategoryName = probCat.s_ProblemCategoryName;
                        probCat.MoveNext();
                    }
                    newProbCat.Save();

                    probCat.Rewind();
                    newProbCat.Rewind();
                    for (int i = 0; i < probCat.RowCount; i++)
                    {
                        probCatMap[probCat.ID] = newProbCat.ID;
                        probCat.MoveNext();
                        newProbCat.MoveNext();
                    }

                    //copy Problems
                    Problems prob = Problems.GetAllActiveProblems(headQuarter.ID);
                    Problems newProb = new Problems();
                    Hashtable probMap = new Hashtable();
                    for (int i = 0; i < prob.RowCount; i++)
                    {
                        if (probCatMap.ContainsKey(prob.CategoryID))
                        {
                            newProb.AddNew();
                            newProb.CategoryID = (int)probCatMap[prob.CategoryID];
                            newProb.BranchID = branch.ID;
                            newProb.Deleted = false;
                            newProb.s_Description = prob.s_Description;
                            newProb.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                            newProb.LastModifiedByUser = SessionUser.ID;
                        }
                        prob.MoveNext();
                    }

                    newProb.Save();

                    prob.Rewind();
                    newProb.Rewind();
                    for (int i = 0; i < prob.RowCount; i++)
                    {
                        probMap[prob.ID] = newProb.ID;
                        prob.MoveNext();
                        newProb.MoveNext();
                    }

                    //Copy Repair Model Problems
                    RepairModelProblems modelProb = RepairModelProblems.GetAllActiveProblem(headQuarter.ID);
                    RepairModelProblems newModelProb = new RepairModelProblems();
                    for (int i = 0; i < modelProb.RowCount; i++)
                    {
                        if (repairModelMap.ContainsKey(modelProb.RepairModelID) && probMap.ContainsKey(modelProb.ProblemID))
                        {
                            newModelProb.AddNew();

                            newModelProb.RepairModelID = (int)repairModelMap[modelProb.RepairModelID];
                            newModelProb.BranchID = branch.ID;
                            newModelProb.ProblemID = (int)probMap[modelProb.ProblemID];
                            newModelProb.s_RPP = modelProb.s_RPP;
                            newModelProb.s_SpecialPrice = modelProb.s_SpecialPrice;
                            newModelProb.s_StandardPrice = modelProb.s_StandardPrice;
                        }
                        modelProb.MoveNext();
                    }

                    newModelProb.Save();

                    //Copy Roles
                    POSSystem.BLL.Roles roles = POSSystem.BLL.Roles.GetAllActiveBranchRoles(headQuarter.ID);
                    POSSystem.BLL.Roles newRoles = new POSSystem.BLL.Roles();
                    for (int i = 0; i < roles.RowCount; i++)
                    {
                        newRoles.AddNew();
                        newRoles.s_RoleName = roles.s_RoleName;
                        newRoles.LastModifiedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                        newRoles.LastModifiedByUser = SessionUser.ID;
                        newRoles.s_Admin = roles.s_Admin;
                        newRoles.BranchID = branch.ID;
                        newRoles.s_Contracts = roles.s_Contracts;
                        newRoles.s_Customers = roles.s_Customers;
                        newRoles.s_Products = roles.s_Products;
                        newRoles.s_Purchase = roles.s_Purchase;
                        newRoles.s_Repair = roles.s_Repair;
                        newRoles.s_Report = roles.s_Report;
                        newRoles.s_Sales = roles.s_Sales;
                        newRoles.s_Suppliers = roles.s_Suppliers;
                        newRoles.SystemAdmin = false;
                        newRoles.EditSales = false;
                        newRoles.Deleted = false;
                        roles.MoveNext();
                    }

                    newRoles.Save();
                }

                tx.CommitTransaction();


                ((Popup)Master).ShowMessage("Saved");
                return true;
            }
            catch (Exception ex)
            {
                branch.RejectChanges();
                branch.Filter = oldFilter;
                tx.RollbackTransaction();
                ((Popup)Master).ShowErrorMessage(ex.Message);
                ErrorLog.WriteToFile("editBranch.aspx.cs", "Save", ex.Message + "\r\n" + ex.StackTrace);
                return false;
            }
        }

        private void LoadInfo()
        {
            try
            {
                branch = new Branches();
                branch.LoadByPrimaryKey(branchID);

                if (!branch.IsColumnNull(Branches.ColumnNames.Name))
                    editBranch.Name = branch.Name;
                if (!branch.IsColumnNull(Branches.ColumnNames.Address))
                    editBranch.Address = branch.Address;
                if (!branch.IsColumnNull(Branches.ColumnNames.ABN))
                    editBranch.ABN = branch.ABN;
                if (!branch.IsColumnNull(Branches.ColumnNames.Phone))
                    editBranch.Phone = branch.Phone;
                if (!branch.IsColumnNull(Branches.ColumnNames.Fax))
                    editBranch.Fax = branch.Fax;
                if (!branch.IsColumnNull(Branches.ColumnNames.Active))
                    editBranch.Active = branch.Active;
            }
            catch (Exception ex)
            {
                ((Popup)Master).ShowErrorMessage(ex.Message);
                ErrorLog.WriteToFile("editBranch.aspx.cs", "LoadInfo", ex.StackTrace);
            }
        }

        public void btnSaveAndClose_OnClick(Object sender, EventArgs e)
        {
            if (Save())
                CloseDlg(1);
        }
    }
}
